package ecommerce.action;

import ecommerce.dao.TagDAO;
import ecommerce.dao.UserDAOImpl;
import ecommerce.dao.TagDAOImpl;
import ecommerce.model.Photo;
import ecommerce.model.Tag;
import ecommerce.dao.UserTagDAOImpl;

import java.io.*;
import java.net.*;
import java.util.*;

import javax.xml.parsers.*;

import org.apache.log4j.Logger;
import org.w3c.dom.*;
import com.opensymphony.xwork2.*;

public class PhotoAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(PhotoAction.class);
	private Photo photo = null;

	public String photoPage() {
		System.setProperty("http.proxyHost", "www-cache.usyd.edu.au");
		System.setProperty("http.proxyPort","8080");
		Map<String, Object> params = ActionContext.getContext().getParameters();
		Map<String, Object> session = ActionContext.getContext().getSession();
		if(getPhotoInfo((((String[])params.get("id"))[0]),(((String[])params.get("secret"))[0])) 
		   && readPhotoInfo())
		{
			if(sessionValidation())
			{
				if(storePhoto((int)((Integer)session.get("current_user"))) 
				   && storeTag((int)((Integer)session.get("current_user")))){
					return SUCCESS;
				}
			}
			else
			{
				return SUCCESS;
			}
		}
		logger.error("Error on displaying full size photo page");
		addFieldError("keyword", "Error occured, please try again!");
		return ERROR;
	}
	
	public boolean storePhoto(int user_id){
		return new UserDAOImpl().updatePhotosViewed(user_id);
	}
	
	public boolean storeTag(int user_id){
		List<String> tags = photo.getPhotoTags();
		TagDAO tagDao = new TagDAOImpl();
		for(int i = 0; i < tags.size(); i++)
		{
			Tag tag = tagDao.getTagByDescription(tags.get(i));
			if(tag == null)
			{
				tag = tagDao.addTag(tags.get(i));
			}
			if(new UserTagDAOImpl().updateUserTagFrequency(user_id, tag.getTagId()) == false)
			{
				return false;
			}
		}
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public boolean sessionValidation()
	{
		Map<String, Object> session = ActionContext.getContext().getSession();
		List<String> photoList = ((List<String>)session.get("photoList")) != null 
									? ((List<String>)session.get("photoList")) 
							        : new ArrayList<String>();
		if(!photoList.contains(photo.getPhotoId()))
		{
			photoList.add(photo.getPhotoId());
			session.put("photoList", photoList);
			return true;
		}
		return false;
	}
	
	public boolean getPhotoInfo(String photo_id, String secret){
		String urlString = "http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=deccef4c74921a3797eac78eebd5c457&photo_id=<photo_id>&secret=<secret>";
		try{
			urlString = urlString.replace("<photo_id>", photo_id);
			urlString = urlString.replace("<secret>", secret);
			
			URL url = new URL(urlString);  
			URLConnection urlConnection = url.openConnection();  
			urlConnection.setConnectTimeout(120000);  
			urlConnection.setReadTimeout(120000);  
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
	        String line=null;  
	        StringBuffer sb = new StringBuffer();
	        while ( (line = reader.readLine()) != null ) {  
	        	sb.append(line);
	        	sb.append("\n");
	        }         
	        reader.close(); 
	        
	        File file = new File("U:\\tempFile_userid_getInfo.xml");
	        PrintWriter pw = new PrintWriter(new OutputStreamWriter
                    (new FileOutputStream(file),"UTF8"));
	        pw.println(sb.toString());
	        pw.close();
	        return true;
		}
		catch(Exception e)
		{
			logger.error("Error on calling Flickr getInfo services " + e);
			return false;
		}
	}
	
	public boolean readPhotoInfo(){
		try 
		{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse("U:\\tempFile_userid_getInfo.xml");
			
		    NodeList nl = doc.getElementsByTagName("photo");
			Element photoInfoElement = (Element)nl.item(0);
			photo = new Photo(photoInfoElement.getAttribute("farm"), photoInfoElement.getAttribute("server"),
					photoInfoElement.getAttribute("id"), "", photoInfoElement.getAttribute("secret"));
			
			nl = doc.getElementsByTagName("owner");
			Element photoOwnerElement = (Element)nl.item(0);
			photo.setPhotoOwner(photoOwnerElement.getAttribute("nsid"));
			
			nl = doc.getElementsByTagName("title");
			Element photoTitleElement = (Element)nl.item(0);
			photo.setPhotoTitle(photoTitleElement.getFirstChild().getNodeValue());
			
			nl = doc.getElementsByTagName("tag");
			List<String> tags = new ArrayList<String>();
			for(int i = 0; i < nl.getLength(); i++)
		    {
				Element tagElement = (Element)nl.item(i);
				tags.add(tagElement.getAttribute("raw"));
		    }
			photo.setPhotoTags(tags);
		    return true;
		} 
		catch (Exception e)
		{
			logger.error("Error on reading getInfo response " + e);
			addFieldError("keyword", "Error on calling Flickr web services");
			return false;
		}    	    
	}
	
	public void setPhoto(Photo photo)
	{
	    this.photo = photo;
	}

    public Photo getPhoto()
    {
    	return this.photo;
    }
	
}
